import os.path
import fnmatch

from projectInfo import *

class ProjectImporter(object):
  def __init__(self):
    pass

  def importFromPath(self, name, path, excludeFolderPatterns=[], excludeFilePatterns=[]):
    if not os.path.exists(path):
      raise Exception('Invalid path: %s' % path)

    proj = ProjectInfo(name, path)
    self.getItems(path, proj, excludeFolderPatterns, excludeFilePatterns)

    return proj

  def getItems(self, path, parent, excludeFolderPatterns=[], excludeFilePatterns=[]):
    folders, files = self.getSubs(path)
    for folder in folders:
      if self.isExcludeItem(folder, excludeFolderPatterns):
        continue
        
      item = ProjectItem(folder, ProjectItemType.Folder, parent)  
      
      parent.getItems().append(item)
      self.getItems(item.getFullname(), item, excludeFolderPatterns, excludeFilePatterns)

    for fi in files:
      if self.isExcludeItem(fi, excludeFilePatterns):
        continue
        
      item = ProjectItem(fi, ProjectItemType.File, parent)
      parent.getItems().append(item)

  def getSubs(self, path):
    files = []
    folders = []

    subs = os.listdir(path)
    for sub in subs:
      subpath = os.path.normpath(path) + os.path.sep + sub
      if os.path.isdir(subpath):
        folders.append(sub)
      elif os.path.isfile(subpath):
        files.append(sub)

    folders.sort()
    files.sort()
    return folders, files
  
  def isExcludeItem(self, item, patterns=[]):
    for pattern in patterns:
      if fnmatch.fnmatch(item, pattern):
        return True
    return False

######################################################################
# test codes
if __name__ == '__main__':
  import sys
  import getopt
  
  def showItem(lst, lvl):
    for item in lst:
      print '%s+- %s: %s' % (' ' * lvl, item.getName(), item.getFullname())
      if len(item.getItems()) > 0:
        showItem(item.getItems(), lvl + 1)

  try:
    opts, args = getopt.getopt(sys.argv[1:], "hd:v", ["help", "path="])
  except getopt.GetoptError, err:
    print 'Get opt failed.%s%s' % (os.linesep, str(err))
    sys.exit(2)

  path = ''
  for opt, arg in opts:
    if opt.lower() == '--path' or opt.lower() == '--p':
      path = os.path.realpath(arg)
      print 'Source Path: %s' % path
      print '------------------------------------'

  if path == '':
    print 'Please enter a file name by \'--path=\' or \'--p\' argument.'
    
  if not os.path.exists(path):
    print 'Can not find the path: %s' % path
    sys.exit(2)

  importor = ProjectImporter()
  proj = importor.importFromPath('wxPyDev', path)
  
  print '%s: %s' % (proj.getName(), proj.getPath())
  showItem(proj.getItems(), 1)
